package com.generic.mybatis.dal.interceptor.automap.builder;

import com.generic.mybatis.dal.interceptor.automap.SqlBuilder;
import com.generic.mybatis.dal.interceptor.automap.TableMapper;
import com.generic.mybatis.dal.interceptor.automap.TableMapperHolder;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.mapping.MappedStatement;

import java.util.Map;

import static com.generic.mybatis.dal.interceptor.automap.builder.SqlBuilderUtil.*;

/**
 * 查询单条记录
 *
 * @author wuaj
 */
public class GetOneBuilder implements SqlBuilder {
    @Override
    public String buildSql(MappedStatement mappedStatement, Class dtoClass, Object object) throws Exception {
        if (null == object) {
            throw new RuntimeException("Sorry,I refuse to build sql for a null object!");
        }
        TableMapper tableMapper = TableMapperHolder.getTableMapper(dtoClass);
        Map dtoFieldMap = PropertyUtils.describe(object);
        SQL sql = buildSelectStatement(tableMapper);
        buildIdWhereStatement(sql, tableMapper, dtoFieldMap);

        replaceResultMap(mappedStatement, tableMapper.getResultMap());
        return sql.toString();
    }
}
